package cn.bugstack.springframework.beans.factory.support;

import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;

/**
 * @author oyz
 */
public abstract  class AbstractAutowireCableBeanFactory extends AbstractBeanFactory{


    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition,Object[] args) throws BeansException {
        Object bean = null;
        try {
            // 其实这块会埋下一个坑，有构造函数入参的对象怎么处理？可以提前思考
            bean = createBeanInstance(beanDefinition,beanName,args);

        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed",e);
        }
        // 把该bean放入ioc容器里边
        addSingleton(beanName,bean);
        return bean;
    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) throws Exception {
        Constructor constructor = null;
        Class beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor ctor:declaredConstructors){
            if(null != ctor&&ctor.getParameterTypes().length == args.length){
                constructor = ctor;
                break;
            }
        }


        return instantiationStrategy.instantiate(beanDefinition,beanName,constructor,args);
    }


}
